#!/usr/bin/env python3
"""
代码风格自动修复脚本
修复Flake8检测到的常见问题
"""

import os
import re
import sys
from pathlib import Path


def fix_file(file_path):
    """修复单个文件的代码风格问题"""
    print(f"修复文件: {file_path}")
    
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    original_content = content
    
    # 1. 移除行尾空白 (W291, W293)
    content = re.sub(r'[ \t]+$', '', content, flags=re.MULTILINE)
    
    # 2. 移除文件末尾多余空行 (W391)
    content = content.rstrip() + '\n'
    
    # 3. 修复导入但未使用的问题 (F401) - 注释掉未使用的导入
    unused_imports = [
        'from typing import Tuple',
        'from pathlib import Path', 
        'import json',
        'from tqdm import tqdm',
        'from sqlparse.sql import Token',
        'from sqlparse.tokens import Keyword, Name, Punctuation',
        'from functools import lru_cache',
        'import re',
        'from typing import Dict',
        'from concurrent.futures import ThreadPoolExecutor, as_completed'
    ]
    
    for import_line in unused_imports:
        if import_line in content and not is_import_used(content, import_line):
            content = content.replace(import_line, f'# {import_line}  # noqa: F401')
    
    # 4. 修复未使用的变量 (F841) - 添加下划线前缀
    content = re.sub(r'(\s+)([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*([^=\n]+)(?=\n.*# F841)', 
                     r'\1_\2 = \3', content)
    
    # 5. 修复缺少空行的问题 (E302, E305)
    # 在类和函数定义前添加两个空行
    content = re.sub(r'\n(class [^:\n]+:)', r'\n\n\1', content)
    content = re.sub(r'\n(def [^:\n]+:)', r'\n\n\1', content)
    
    # 6. 修复算术运算符周围缺少空格 (E226)
    content = re.sub(r'(\w)([+\-*/])(\w)', r'\1 \2 \3', content)
    
    # 7. 修复bare except (E722)
    content = re.sub(r'except:', 'except Exception:', content)
    
    # 只有内容发生变化才写入文件
    if content != original_content:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f"  ✅ 已修复")
        return True
    else:
        print(f"  ⏭️  无需修复")
        return False


def is_import_used(content, import_line):
    """检查导入是否被使用"""
    # 简单检查：提取导入的名称并在内容中搜索
    if 'from' in import_line:
        # from module import name
        match = re.search(r'from .+ import (.+)', import_line)
        if match:
            names = [name.strip() for name in match.group(1).split(',')]
            for name in names:
                if name in content.replace(import_line, ''):
                    return True
    else:
        # import module
        match = re.search(r'import (.+)', import_line)
        if match:
            module = match.group(1).strip()
            if module in content.replace(import_line, ''):
                return True
    
    return False


def main():
    """主函数"""
    project_root = Path(__file__).parent.parent
    src_dir = project_root / 'src'
    
    print("🔧 开始修复代码风格问题...")
    
    fixed_count = 0
    total_count = 0
    
    # 修复src目录下的所有Python文件
    for py_file in src_dir.glob('*.py'):
        total_count += 1
        if fix_file(py_file):
            fixed_count += 1
    
    print(f"\n📊 修复完成:")
    print(f"   - 总文件数: {total_count}")
    print(f"   - 已修复: {fixed_count}")
    print(f"   - 无需修复: {total_count - fixed_count}")


if __name__ == '__main__':
    main()
